package dom4j;

import java.io.File;


import java.io.FileOutputStream;
import java.lang.ProcessBuilder.Redirect;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;


public class Demo1 {
  @Test
	public void  read() throws Exception{
		SAXReader reader = new SAXReader();
	Document document=	reader.read(new File("src/book.xml"));
		Element root = document.getRootElement();
		
		String bookName= root.element("书").attributeValue("name");
		System.out.println(bookName);
	}
  
  @Test
  public void add() throws Exception{
		SAXReader reader = new SAXReader();
		Document document=	reader.read(new File("src/book.xml"));
		Element price = DocumentHelper.createElement("售价");
		price.setText("1300元");
		document.getRootElement().element("书").add(price);
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format);
		writer.write(document);
		writer.close();
  }

@Test
public void update() throws Exception{
	SAXReader reader = new SAXReader();
	Document document = reader.read("src/book.xml");
	Element price = (Element) document.getRootElement().element("书").elements("售价").get(1);
	price.setText("209元");
	OutputFormat format = OutputFormat.createPrettyPrint();
	format.setEncoding("utf-8");
	XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format);
	writer.write(document);
	writer.close();
	
}
	
@Test 
public void delete() throws Exception{
	SAXReader reader = new SAXReader();
	Document document = reader.read("src/book.xml");
	Element price = (Element) document.getRootElement().element("书").elements("售价").get(0);
	price.getParent().remove(price);
	OutputFormat format = OutputFormat.createPrettyPrint();
	format.setEncoding("utf-8");
	XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format);
	writer.write(document);
	writer.close();
	
}

@Test
public void findWithXpath() throws Exception{
	SAXReader reader = new SAXReader();
	Document document = reader.read("src/book.xml");
	Element element=(Element) document.selectNodes("//书名").get(0);
	System.out.println(element.getText());
	
}

	@Test 
	public void findUsers() throws Exception{
		String userName="xiayq";
		String pass= "123";
		SAXReader reader= new SAXReader();
		Document document = reader.read("src/users.xml");
		Element element = (Element) document.selectSingleNode("//user[@name='"+userName+"' and @password='"+pass+"']");
	    if (element!=null) {
			System.out.println("登陆成功");
		}else {
			System.out.println("用户名和密码不匹配");
		}
	}
}
